package com.lagou.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host.address}")
    private String elasticsearchHostAddress;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        /**
         * 解析配置信息，获取elasticsearch主机地址
         */
        String[] hostAddressArray = elasticsearchHostAddress.split(",");
        HttpHost[] httpHostArray = new HttpHost[hostAddressArray.length];
        for (int i = 0; i < hostAddressArray.length; i++) {
            String hostAddress = hostAddressArray[i];
            httpHostArray[i] = new HttpHost(hostAddress.split(":")[0], Integer.parseInt(hostAddress.split(":")[1]), "http");
        }
        /**
         * 创建RestHighLevelClient对象
         */
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }
}
